qui(
    function (require, exports, module) {
        Program.Grid = function (options) {
            this.dao = Program.Dao;
            this.task = Program.Task;
            this.config = Program.Config;
            this.options = options || {};
        };
        Com.inherits(Program.Grid, Ancestor.Grid).extend({
            /* program library start*/
            runLibrary: function () {
                var self = this;
                self.$grid = self.options.$grid;
                self.$feedGrid = self.options.$feedGrid;
                var taskArr = [];
                taskArr.push(self.task.getLiveProgramType(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.getLiveChannelType(self.dao.cfgName.liveChannelType));
                taskArr.push(self.task.getLiveType(self.dao.cfgName.LiveType));
                taskArr.push(self.task.getLogType(self.dao.cfgName.LogType));
                taskArr.push(self.task.getGradeType(self.dao.cfgName.episodeGradeType));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                self.config.oaTest = Com.url.getParameter("oatest")==="1";
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startLibrary();
                })
                self.config.PageBeanFeed = Program.Util.createPageBean();
                self.initRecommendRate();
                self.initLibraryAuth();
            },
            initLibraryAuth:function(){
                var self = this;
                self.readyCount = 0;
                self.finalCount = 2;
                self.initOver = false;
                auth.getAuthData({tips: 1, url: '/epg/auth/forceCheck'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_FORCE_CHECK = true;
                    }
                    self.phaseOver();
                })
                auth.getAuthData({tips: 1, url: '/epg/auth/feedView'}, function (rt) {
                    if (rt == null) {
                        self.config.AUTH_FEED_VIEW = true;
                    }
                    self.phaseOver();
                })
            },
            phaseOver: function () {
                var self = this;
                self.readyCount++;
                if (!self.initOver && self.readyCount == self.finalCount) {
                    self.initOver = true;
                    EpgWeb.ajaxQueue.startLoad();
                }
            },
            startLibrary: function (options, callback) {
                var self = this;
                self.bindBasicEvent();
                self.initFeedDialog();
                console.log("load complete startLibrary");
                EpgWeb.Util.bindDate("startDate", "endDate");
                var currentDate = new Date()
                currentDate.setHours(0);
                currentDate.setSeconds(0);
                currentDate.setMinutes(0);
                currentDate.setTime(currentDate.getTime() - 2 * 86400000);
                $("input[name=startDate]").datetimepicker("setDate", currentDate);
                self.initLibraryGrid.call(self, {}, callback);
                self.initFeedGrid.call(self, {}, callback);
            },

            initLibraryGrid: function (options, callback) {
                var self = this;
                var params = self.getParam();
                var gridConfig = self.getGridConfig(self.config.TABLE_LIBRARY);
                //params.rowNum=10;
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);
                self.echoQuery();
            },

            initFeedGrid:function(options, callback){
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_FEED);
                self.$feedGrid.jqGrid(gridConfig);
            },

            echoQuery: function () {
                var self = this;
                self.query();
            },

            query: function (callback) {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                params.sortType = "desc";
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },

            reload: function () {
                var self = this;
                var $grid = self.$grid;
                $grid.trigger('reloadGrid');
            },

            getParam: function () {
                var self = this;
                var $container = self.options.$container;

                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });

                var name;
                var key;
                $.each($elements, function () {
                    name = this.name;
                    if (name) {
                        if (this.type == 'radio') {
                            params[name] = $('input[name="' + name + '"]:checked').val() || '';
                        } else
                            params[name] = $.trim($(this).val()) || '';
                    }
                });
                var formal = Com.url.getParameter("formal");
                if (formal) {
                    params.formal = formal;
                }
                params.fromPath = "library";
                var today = Com.url.getParameter("today");
                if (today) {
                    $('#absToday').show();
                    $('#absToday+').show();
                }
                return params;
            },

            bindBasicEvent: function () {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                $form.find('.query-btn').on('click', function () {
                    self.query();
                    return false;
                });
                $form.find('button[type="reset"]').click(function () {
                    $("select[name=liveChannelType]").hide();
                    self.resetQueryForm();
                    self.updateFormLayoutWithLiveType(0);
                });

                $form.find('select[name=liveType]').bind("change", function (event) {
                    var $curTarget = $(event.currentTarget);
                    var selectedValue = $curTarget.val();
                    self.updateFormLayoutWithLiveType(selectedValue);
                });
                self.updateFormLayoutWithLiveType(0);

                //$form.find("select[name=playStatus]").val(1);

            },
            initDialog: function () {
                var self = this;
                $("#modifyDiv").dialog({
                    title: "打点项目明细",
                    autoOpen: false,
                    width: 500,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function () {
                        $("#modifyDiv").find("form").trigger("reset");
                        $("#modifyDiv").find("input[name=channel_code]").removeAttr("readonly");
                        $("#modifyDiv").find("input[name=channel_addr]").removeAttr("readonly");
                        $("#modifyDiv").find("select[name=server_region2]").change();
                    }
                });
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },
            initFeedDialog:function(){
                $("#feedDiv").dialog({
                    title: "查看已发布feed",
                    autoOpen: false,
                    width: 820,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false
                });
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },

            /* program library end */
            /* program list start  */
            runDayList: function (options, callback) {
                var self = this;
                self.$grid = $('#list');
                var taskArr = [];
                taskArr.push(self.task.getLiveProgramType(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.getLiveChannelType(self.dao.cfgName.liveChannelType));
                taskArr.push(self.task.getLiveType(self.dao.cfgName.LiveType));
                taskArr.push(self.task.getLogType(self.dao.cfgName.LogType));
                taskArr.push(self.task.getGradeType(self.dao.cfgName.episodeGradeType));
                var fatherId = Com.url.getParameter("fatherId");
                if (EpgWeb.Plugin.Validate.checkNum(fatherId)) {
                    self.dao.channelId = Number(fatherId);
                    taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, {id: fatherId}));
                }
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startDayList();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            startDayList: function (options, callback) {
                var self = this;
                $("button[name=newProgram]").hide();
                $("button[name=tvmaoCall]").hide();
                var element = self.dao.getChannel()
                if (element != null) {
                    switch (element.liveType) {
                        case 1:
                            //  $("button[name=tvmaoCall]").show();
                            break;
                        case 2:
                            $("button[name=newProgram]").show();
                            break;
                    }
                }
                self.initDayList({});
                self.bindListBasicEvent()
                self.initWeekToolBar();
            },
            initDayList: function (options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST);
                self.$grid.jqGrid(gridConfig);
                self.bindDayTListEvent();
                //self.echoQuery();
            },

            listQuery: function () {
                var self = this;
                var $grid = self.$grid;
                var params = self.getListParam();
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },
            getListParam: function () {
                var self = this;
                return  {
                    startDate: Program.Config.dateTime + " 00:00:00",
                    endDate: Program.Config.dateTime + " 23:59:59",
                    fatherId: self.dao.channelId,
                    fromPath: "library",
                    pageSize: 40}
            },

            initWeekToolBar: function () {
                var self = this;
                Program.Util.WeekManager = EpgWeb.Util.createWeekManager($("#dayRange div label"));
                var weekRangeLabel = $("#weekRange label");
                $(weekRangeLabel[0]).bind("click", function () {
                    Program.Util.WeekManager.preWeek();
                });
                $(weekRangeLabel[1]).bind("click", function () {
                    self.updateTableByDate(Program.Util.WeekManager.quickToCurrentWeek());
                })
                $(weekRangeLabel[2]).bind("click", function () {
                    Program.Util.WeekManager.nextWeek()
                })
                $("button.left").bind("click", function () {
                    Program.Util.WeekManager.preWeek()
                })

                $("button.right").bind("click", function () {
                    Program.Util.WeekManager.nextWeek()
                })

                $("#dayRange div label").bind("click", function (event) {
                    var aChild = event.currentTarget;
                    $(aChild).parent().find("label").removeClass("selected");
                    $(aChild).addClass("selected");
                    self.updateTableByDate(aChild.getAttribute("query-date"))
                })
                self.updateTableByDate(Program.Util.WeekManager.quickToCurrentWeek());
            },

            updateTableByDate: function (lDateFormat) {
                var self = this;
                Program.Config.dateTime = lDateFormat;
                self.$grid.setGridParam({page: 1, url: EpgWeb.urlConfig.programList, loadtext: '加载中...',
                    datatype: "json",
                    loadui: "block", postData: self.getListParam()}).trigger("reloadGrid");
            },

            bindListBasicEvent: function () {
                var self = this;
                $("button[name=newProgram]").bind("click", function (event) {
                    Program.Util.jumpListToAdd(self.dao.channelId);
                })
                $("button[name=tvmaoCall]").removeAttr("disabled");
                $("button[name=tvmaoCall]").bind("click", function (event) {
                    $("button[name=tvmaoCall]").prop("disabled", true);
                    self.syncQuery(self.dao.channelId)
                })
            },

            bindDayTListEvent: function () {
                var self = this;
                $("<span style='color:#187ddb;font-weight:normal'>提示：直播视频只能回看二天！</span>").appendTo($("#t_list"));
                var bdiv = $(".ui-jqgrid-bdiv");
                $("<label style='width: 40px;float:right;'>PM</label>").bind("click", function () {
                    if (bdiv[0].scrollHeight <= bdiv[0].clientHeight) {
                        return;
                    }
                    var allDate = self.$grid.jqGrid("getRowData");
                    var checkPM = "";
                    var interrupt = 0;
                    for (var i = 0; i < allDate.length; i++) {
                        checkPM = allDate[i].startPlayTime.substr(11);
                        if (checkPM >= "12:00:00") {
                            interrupt = i;
                            break;
                        }
                    }
                    bdiv.scrollTop(interrupt / allDate.length * bdiv[0].scrollHeight)
                }).appendTo($("#t_list"));
                $("<label style='width: 40px;float:right;'>AM</label>").bind("click", function () {
                    bdiv.scrollTop(0)
                }).appendTo($("#t_list"))
            },

            /* program list end  */

            /* program grid operation  */
            syncQuery: function (fatherId) {
                var self = this;
                self.dao.syncTVmaoPrograms({fatherId: fatherId}, function (data) {
                    SystemDialog.queryAlert(data.msg);
                    if (data.code == "A00000") {
                        $("button[name=tvmaoCall]").removeAttr("disabled");
                        self.reload();
                    }
                })
            },

            initRecommendRate: function () {
                var self = this;
                var selectJDom = $("select[name=recommendRate]");
                $("<option>", {value: '', html: "全部", selected: true}).appendTo(selectJDom);
                $.each(Program.Config.RECOMMEND_RATE, function (index, obj) {
                    $("<option>", {
                        value: index,
                        html: obj
                    }).appendTo(selectJDom);
                });
            },

            updateFormLayoutWithLiveType: function (val) {
                if (val == 2) {
                    //$("#recommendRateDiv").show();
                    $("#hotDiv").show();
                    $("#testDiv").show();
                } else {
                    //$("#recommendRateDiv").hide();
                    $("#hotDiv").hide();
                    $("#testDiv").hide();
                }
            }
        })
    }
);